import React, { useState, useEffect } from 'react';
import { Input, Button } from 'antd';
import AcceptModal from './acceptModal';
import './index.less';

const ChooseUser = ({ userIds, userNames, readOnly, onUserChange }) => {
  const [acceptVisible, setAcceptVisible] = useState(false);
  const [acceptId, setAcceptId] = useState([]);
  const [acceptName, setAcceptName] = useState([]);

  useEffect(() => {
    if (userIds) {
      setAcceptId(
        userIds.split(',').map((id) => {
          return id;
        }),
      );
      setAcceptName(
        userNames.split(',').map((name) => {
          return name;
        }),
      );
    }
  }, [userIds]);

  // 打开选择接收人窗口
  const showModal = () => {
    setAcceptVisible(true);
  };
  const acceptCreate = (values) => {
    acceptCancelFn();
    let userList = values.userList;
    let userIds = [];
    let userNames = [];
    userList.forEach((el) => {
      if (el.userList) {
        el.userList.forEach((element) => {
          if (values.ids.includes(element.treeId)) {
            userIds.push(element.treeId);
            userNames.push(element.treeName);
          }
        });
      }
    });
    setAcceptId(userIds);
    setAcceptName(userNames);
    onUserChange({ userIds, userNames });
  };
  const acceptCancelFn = () => {
    setAcceptVisible(false);
  };

  return (
    <>
      <Button type="primary" onClick={showModal} disabled={readOnly}>
        请选择
      </Button>
      <Input className="acceptNames" readOnly value={acceptName}></Input>
      <AcceptModal
        visible={acceptVisible}
        checkedIds={acceptId}
        onCreate={acceptCreate}
        onCancel={acceptCancelFn}
      ></AcceptModal>
    </>
  );
};
export default ChooseUser;
